package com.nescafe.nescafepromo.command.admin;

import java.util.ArrayList;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.nescafe.nescafepromo.command.Command;
import com.nescafe.nescafepromo.command.CommandException;
import com.nescafe.nescafepromo.entity.EntityType;
import com.nescafe.nescafepromo.entity.Participant;
import com.nescafe.nescafepromo.entity.Purchase;
import com.nescafe.nescafepromo.entity.TotalPoints;
import com.nescafe.nescafepromo.model.NPRequest;
import com.nescafe.nescafepromo.model.NPResponse;

public class AddPurchase implements Command {

	@Override
	public NPResponse execute(NPRequest req) throws CommandException {
		NPResponse res = null;
		Transaction txn = null;
		try {
			String email = req.getParam("email");
			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			ArrayList<Entity> entities = new ArrayList<Entity>();

			txn = ds.beginTransaction();

			Key participantKey = EntityType.PARTICIPANT.getKey(email);
			Key totalPointsKey = EntityType.TOTAL_POINTS.getKey(participantKey, email);

			// Entity participantEntity = null;
			// Entity totalPointsEntity = null;
			TotalPoints totalPoints = null;
			try {
				// participantEntity =
				ds.get(participantKey);
				totalPoints = new TotalPoints(ds.get(totalPointsKey));
			} catch (EntityNotFoundException e) {
				Participant participant = new Participant(email);
				// participantEntity = participant.toEntity();
				entities.add(participant.toEntity());

				totalPoints = new TotalPoints(participantKey);
			}

			// store purchase
			float amount = Float.parseFloat(req.getParam("amount"));
			int pointEquivalent = (int) amount / 10;

			Purchase p = new Purchase(req.getParam("receipt_no"), participantKey);
			p.setReceiptDate(Integer.parseInt(req.getParam("receipt_time")));
			p.setBranch(Integer.parseInt(req.getParam("branch")));
			p.setEmail(email);
			p.setAmount(amount);
			p.setPoints(pointEquivalent);
			entities.add(p.toEntity());

			// update points
			long newTotal = totalPoints.getTotalPonts() + pointEquivalent;
			totalPoints.setTotalPonts(newTotal);
			entities.add(totalPoints.toEntity());

			ds.put(entities);

			txn.commit();
			res = new NPResponse("Successfully added purchase.");
		} catch (Exception e) {
			if (txn != null && txn.isActive()) {
				txn.rollback();
			}
			throw new CommandException(e.getMessage());
		}

		return res;
	}

}
